from django.shortcuts import get_object_or_404
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django.http.request import QueryDict
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend

from .models import camera
from .serializers import CameraSerializer

# Create your views here.

class CameraPagination(PageNumberPagination):
    page_size_query_param = 'pageSize'
    page_query_param = 'pageIndex'

class CameraViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = camera.objects.all()
    serializer_class = CameraSerializer
    pagination_class = CameraPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['ip']

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if request.data['rtsp'] == '':
            request.data['rtsp'] = 'rtsp://{}:{}@{}/1/h264major'.format(request.data['user'], request.data['password'], request.data['ip'])
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data={'data':serializer.data, 'message':'成功', 'code': '0000'}, status=status.HTTP_201_CREATED, headers=headers)
    
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return Response(data={'data':{'total': len(queryset), 'list': serializer.data}, 'message':'成功', 'code': '0000'}, status=status.HTTP_200_OK)

        serializer = self.get_serializer(queryset, many=True)
        return Response(data={'data':{'total': len(queryset), 'list': serializer.data}, 'message':'成功', 'code': '0000'}, status=status.HTTP_200_OK)
    
    # def destroy(self, request, *args, **kwargs):
    #     instance = self.get_object()
    #     self.perform_destroy(instance)
    #     return Response(status=status.HTTP_204_NO_CONTENT)
    
    @action(methods=['post'], detail=False)
    def delete(self, request,  *args, **kwargs):
        delete_id = request.query_params.get('ids', None)
        if not delete_id:
            return Response(status=status.HTTP_404_NOT_FOUND)
        for i in delete_id.split(','):
            get_object_or_404(camera, pk=int(i)).delete()
        return Response(data={'data':{'total':0}, 'message':'成功', 'code': '0000'}, status=status.HTTP_200_OK)
    
    @action(methods=['post'], detail=False)
    def fileupload(self, request,  *args, **kwargs):
        user = 'admin'
        password = 'admin'
        textFile = request.FILES["file"]
        textLines = textFile.readlines()
        for textLine in textLines:
            textLine = textLine.decode('utf-8')
            textLine = textLine.strip()
            textLine = textLine.split('<IPAddress>')[1]
            textLine = textLine.split('</IPAddress>')[0]
            
            newData = QueryDict(mutable=True)
            newData.update({'ip': textLine})
            newData.update({'user': user})
            newData.update({'password': password})
            newData.update({'delay': 1})
            newData.update({'notes': ''})
            rtsp = 'rtsp://{}:{}@{}/1/h264major'.format(user, password, textLine)
            newData.update({'rtsp': rtsp})
            serializer = self.get_serializer(data=newData)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
        return Response(data={'data':{'total':0}, 'message':'成功', 'code': '0000'}, status=status.HTTP_200_OK)